﻿using System;
using System.Net;
using System.Net.Mail;

namespace tjb.Utility
{
    /// <summary>
    /// 
    /// </summary>
    public static class Mail
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Host"></param>
        /// <param name="Port"></param>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static bool SendMail(string Host, int Port, string UserName, string Password, MailMessage Message)
        {
            return SendMail(Host, Port, 0, false, UserName, Password, Message, true, null);
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Host">发送邮件服务器</param>
        /// <param name="Port">发送邮件端口</param>
        /// <param name="Timeout">超时时间</param>
        /// <param name="UserName">用户名</param>
        /// <param name="PassWord">密码</param>
        /// <param name="Message">邮件内容。必须指定发件人</param>
        /// <param name="EnableSsl"></param>
        /// <param name="IsSync">是否同步，同步为true，异步为false，web下无法异步发送邮件</param>
        /// <param name="CompletedCallBack">异步发送邮件完成时执行的函数</param>
        /// <returns>发送过程是否出错</returns>
        public static bool SendMail(string Host, int Port, int Timeout, bool EnableSsl, string UserName, string PassWord, MailMessage Message, bool IsSync, SendCompletedEventHandler CompletedCallBack)
        {

            if (string.IsNullOrEmpty(Host))
                return false;


            SmtpClient mailClient = new SmtpClient(Host);
            if (Port > 0)
                mailClient.Port = Port;

            mailClient.UseDefaultCredentials = false;
            if (string.IsNullOrEmpty(UserName))
                return false;
            if (PassWord == null)
                return false;
            mailClient.Credentials = new NetworkCredential(UserName, PassWord);
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            if (Timeout > 0)
                mailClient.Timeout = Timeout;

            mailClient.EnableSsl = EnableSsl;
            try
            {
                if (IsSync)
                {
                    mailClient.Send(Message);
                }
                else
                {
                    if (CompletedCallBack != null)
                        mailClient.SendCompleted += CompletedCallBack;
                    mailClient.SendAsync(Message, Message);
                }
                return true;
            }
#if DEBUG
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return false;
            }
#else
            catch
            {
                return false;
            }
#endif

        }
    }
}
